package com.mjk.common.web.getway.utils;

import com.mjk.common.base.error.BeeError;
import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.tools.gson.GsonUtils;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.util.FileUtils;
import com.mjk.common.util.MDCUtils;
import com.mjk.common.util.ObjectUtils;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;

import java.io.*;
import java.util.Map;

/**
 * 返回数据 工具类
 * @author mjk
 *
 */
public class ResponseUtils {
	/**
	 * 回写请求数据
     */
	public static boolean returnGetWay(HttpServletResponse response, Object o){
		return returnGetWay(response, o,"");
	}
	
	public static boolean returnGetWay(HttpServletResponse response,Object o,String type){
		try(PrintWriter out = response.getWriter();){
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-Type", "text/html;charset=UTF-8");
			//修改如果o是空的情况下，返回数据为null的情况
			if(ObjectUtils.isEmpty(o)){
				BeeResponse rsp = BeeError.BEE_ERROR_FOR_ADMIN.tranceError();
				rsp.setTraceId(MDCUtils.getTraceId());
				out.println(GsonUtils.bean2Json(rsp));
			}else {
				if ("3".equals(type)) {
					if (o instanceof String) {
						out.print(GsonUtils.json2Xml(o.toString()));
					} else {
						out.print(GsonUtils.json2Xml(GsonUtils.bean2Json(o, BeeRoleUtils.isComplete.get())));
					}
				} else {
					if (o instanceof String) {
						out.print(o);
					} else {
						out.print(GsonUtils.bean2Json(o, BeeRoleUtils.isComplete.get()));
					}
				}
			}
		}catch(Exception e){
			BizLogger.error(e);
		}
		return false;
	}
	/**
	 * 出参转化
     */
	public static boolean returnGetWay(HttpServletResponse response,Object o,Map<String,String> mapping){
		try{
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-Type", "text/html;charset=UTF-8");				
			PrintWriter out = response.getWriter();
			if(o instanceof String){
				out.print(o);
			}else{
				String json = GsonUtils.bean2Json(o);
				out.print(GsonUtils.replaceKey(json, mapping));
			}
			out.close();
		}catch(Exception e){
			BizLogger.error(e);
		}
		return false;
	}
	/**
	 * 下载文件
	 */
	public static void downFile(HttpServletResponse response,BeeResponse rsp, String fileName) {
		response.setContentType("multipart/form-data");
		String downName = fileName.contains("_") ? fileName.split("_")[1] : fileName;
		response.setHeader("Content-Disposition", "attachment;fileName=" + downName);
		try (ServletOutputStream outputStream = response.getOutputStream()) {
			if (rsp.getData() instanceof byte[] bytes) {
				outputStream.write(bytes);
			} else {
				outputStream.write(new byte[0]);
			}
		} catch (IOException e) {
			try (PrintWriter out = response.getWriter();) {
				out.println(GsonUtils.bean2Json(BeeError.SYSTEM_FILE_CONTEXT_IS_NULL.tranceError(), true));
			} catch (Exception e1) {
				BizLogger.error(e1);
			}
		}finally {
			//删除文件
			FileUtils.del(new File(fileName).toPath());
		}
	}
}
